package cn.bytecollege.admin.filter;

import cn.bytecollege.common.entity.Admin;
import cn.bytecollege.common.entity.Merchant;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Liao
 * 是否有效的登录,拦截形如直接admin/index.jsp，直接添加商品的操作。
 */
@WebFilter(filterName = "SuperAdminAccessValidFilter",value = "/super/*")
public class SuperAdminAccessValidFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //固定操作
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String uri = req.getRequestURI();
        if (uri.contains("/super/login")){
            chain.doFilter(request,response);
            return;
        }

        HttpSession session = req.getSession();
        Admin admin = (Admin) session.getAttribute("admin");
        if (admin == null){
            //没有登录
            //request.getRequestDispatcher(Resource.PAGE_LOCATION+"/admin/login.jsp").forward(request,response);
            resp.sendRedirect(req.getContextPath()+"/super/login");
            return;
        }
        chain.doFilter(request,response);
    }

    @Override
    public void destroy() {}
}
